export function mapFormatCoord(format, element, compositionCoord) {
  const { compWidth, compHeight } = calcCompSize(compositionCoord);
  const compAspectRatio = compWidth / compHeight;
  const elemCoord = calcElemCoord(format, element, compAspectRatio);
  const { compositionId } = element

  return { ...elemCoord, compositionId, compositionWdith: compWidth }
}

function calcElemCoord(format, element, aspectRatio) {
  const { suite: { usePercentSize, based }, width: pageWidth, height: pageHeight } = format
  const basedSizes = {
    short: pageWidth < pageHeight ? pageWidth : pageHeight,
    width: pageWidth,
    height: pageHeight
  }
  const scale = usePercentSize ? basedSizes[based] / 100 : 1
  let { width, height, left, center, right, top, middle, bottom } = element
  let x = 0, y = 0;
  if (element.width) {
    width = width * scale
    height = width / aspectRatio
  }
  if (element.height) {
    height = height * scale
    width = height * aspectRatio
  }

  if (left || left == 0) {
    x = left * scale
  }

  if (center || center == 0) {
    x = pageWidth / 2 - width / 2
  }

  if (right || right == 0) {
    x = pageWidth - width - right * scale
  }

  if (top || top == 0) {
    y = top * scale
  }

  if (middle || middle == 0) {
    y = pageHeight / 2 - height / 2
  }

  if (bottom || bottom == 0) {
    y = pageHeight - height - bottom * scale
  }
  return { x, y, width, height }
}

function calcCompSize(coordinates) {
  let compWidth = 0; let compHeight = 0;
  for (const key in coordinates) {
    const { x, y, width, height } = coordinates[key];
    if (compWidth < x + width) { compWidth = x + width }
    if (compHeight < y + height) { compHeight = y + height }
  }
  return { compWidth, compHeight }
}

// Example usage
export const format =
{
  "id": 1,
  "name": "a5",
  "brandId": 1,
  "suiteId": 1,
  "width": 145,
  "height": 285,
  "backgroundColorId": 3,
  "elements": [
    {
      "compositionId": 1,
      "schemeId": 2,
      "height": 1,
      "left": 1,
      "top": 1
    },
    {
      "compositionId": 2,
      "schemeId": 2,
      "width": 0,
      "left": 1,
      "top": 1,
      "height": 1,
      "right": 1
    }
  ],
  "suite": {
    "id": 1,
    "brandId": 1,
    "name": "print",
    "medium": "print",
    "based": "short",
    "usePercentSize": true,
    "unit": "mm",
    "colorMode": "cmyk"
  }
}



